#include "encodeur.h"



int main(int argc, char** argv){
	char** list;
	int listsize;
	char** file;
	char* newFile = NULL;	

	parseArgAndDupFiles(argc,argv,DUP_IN | DUP_OUT, NULL, NULL);



	while(1){
		if(!askListToServer(stdin,&list,&listsize)){
			logMessage(stderr,"Server doesn't responded, try again\n");
			sleep(ENCODEUR_DELAI);
			continue;
		}

		file = choseFile(&list,listsize,canConvert);
		if(listsize == 0 || file == NULL || *file == NULL){
			logMessage(stderr,"Empty list, nothing to do, going idle\n");
			sleep(ENCODEUR_DELAI);
			continue;
		}
		logMessage(stderr,"Will try to lock the file\n",*file);
		if(!lockFile(file)){ 
			logMessage(stderr,"File is already locked, search for another: %s\n",*file);
			continue;
		}else{
			logMessage(stderr,"Succesfully Locked file %s\n",*file);
		}
		convertFile(file,&newFile);

		logMessage(stderr,"File Converted, cleaning locks and moving file to server\n");
		if(!unlockFile(file)){ 
			logMessage(stderr,"it was not possible to unlock the file %s\n",*file);
		}
		if(sendOperation(stdin,stdout,OP_DEL,*file) == 0){
			logMessage(stderr,"it was not possible to remove the original file %s\n",*file);
		}

		if(sendOperation(stdin,stdout,OP_ADD,newFile) == 0){
			logMessage(stderr,"it was not possible to send the file %s\n",newFile);
		}else{
			logMessage(stderr,"File successfully converted and moved to server %s\n",newFile);
		}
		free(newFile);
		newFile = NULL;
		file = NULL;
	}
	exit(EXIT_SUCCESS);
}




int searchFile(char*** fileList, int sizeL ,char* file){
	int i;
	for(i = 0; i< sizeL; i++){
		if(strstr((*fileList)[i],file) == ((*fileList)[i])){
			return i;
		}
	}
	return i;
}

int canConvert(char*** fileList,int sizeL,char* file){
	char* nameLock;
	int filelen = strlen(file);
	int result = 1;
	if( strstr(file+filelen-3, "ged") != NULL)
		return 0;
	convertExt(file, "blk" ,&nameLock);;
	/* there's a lock */
	if(searchFile(fileList,sizeL,nameLock) < sizeL) 
		result = 0;
	free(nameLock);
	nameLock = NULL;
	return result;
}

int     lockFile(char**  file){
	char* newFile; 
	int success = 1;
	convertExt(*file, "blk",&newFile);
	if(sendOperation(stdin,stdout,OP_ADD,newFile) == 0){
		success = 0;
	}
	free(newFile);
	newFile = NULL;
	return success;
}

void  convertFile(char** file,char** newFile){
	convertExt(*file, "ged",newFile);
 	sleep(CODEUR_DELAI); 
}

int     unlockFile(char** file){
	char* newFile;
	int success = 1;
	convertExt(*file,"blk",&newFile);
	success = sendOperation(stdin,stdout,OP_DEL,newFile);
	free(newFile);
	return success;
}

void  convertExt(char* oldName, char* ext, char** newFile){
	int i,len = strlen(oldName);
	int extlen = strlen(ext);
	for(i = len-1;i>=0;i--){
		if((oldName)[i] == '.'){
			i--;
			break;
		}
	}
	i++;
	if(i == 0){
		i = len;
	}
	i++;
	*newFile = (char*)malloc((1+i+extlen)*sizeof(char));
	strncpy(*newFile,oldName,i);
	strncpy(*newFile+i,ext,extlen);

	(*newFile)[--i] = '.';
	(*newFile)[i+extlen+1] = '\0';
	
}


